package com.bootdo.app;

import com.alibaba.fastjson.JSON;
import com.bootdo.common.utils.AppR;
import com.bootdo.common.utils.CodeUtils;
import com.bootdo.goods.service.TGoodsAllocationService;
import com.bootdo.message.domain.MessageDO;
import com.bootdo.message.service.MessageService;
import com.bootdo.provider.domain.GoodsInfoDO;
import com.bootdo.provider.service.GoodsInfoService;
import com.bootdo.provider.service.ProviderInfoService;
import com.bootdo.put.dao.PutStorageDetailDao;
import com.bootdo.put.domain.PutStorageDO;
import com.bootdo.put.domain.PutStorageDetailDO;
import com.bootdo.put.domain.dto.PutGoodsDto;
import com.bootdo.put.domain.dto.PutStorageDto;
import com.bootdo.put.service.PutStorageDetailService;
import com.bootdo.put.service.PutStorageService;
import com.bootdo.shop.domain.ShopDO;
import com.bootdo.shop.service.ShopService;
import com.bootdo.staff.domain.StaffUserDO;
import com.bootdo.staff.service.StaffUserService;
import org.apache.ibatis.annotations.Update;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import scala.App;

import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/api/put/storage")
@CrossOrigin
public class AppPutStorageController {


    @Autowired
    private ProviderInfoService providerInfoService;
    @Autowired
    private GoodsInfoService goodsInfoService;
    @Autowired
    private PutStorageService putStorageService;
    @Autowired
    private PutStorageDetailService putStorageDetailService;
    @Autowired
    private TGoodsAllocationService tGoodsAllocationService;
    @Autowired
    private StaffUserService staffUserService;
    @Autowired
    private MessageService messageService;
    @Autowired
    private ShopService shopService;


    /**
     * 获取供应商列表
     * @return
     */
    @GetMapping("/provider")
    @ResponseBody
    public AppR getProvider (){
        Map<String,Object> map = new HashMap<>();
        Map<String,Object> h= new HashMap<>();
        h.put("list",providerInfoService.list(map));
        return AppR.ok(h);
    }


    /**
     * 根据商品码查询商品信息
     * @return
     */
    @GetMapping("getGoods")
    @ResponseBody
    public AppR getGoods(@RequestParam String goodsCode,@RequestParam String providerId){
        Map<String,Object> map = new HashMap<>();
        map.put("goodsCode", goodsCode);
        map.put("providerId",providerId);

        GoodsInfoDO goodsInfoDO =goodsInfoService.getGoodsBySku(map);
        if(goodsInfoDO==null)
            return AppR.error(CodeUtils.NO_GOODS,"商品尚未录入，请联系信息员录入商品！");


        Map<String,Object> map1 = new HashMap<>();
        map1.put("goods",goodsInfoDO);
        map1.put("boxNumber",goodsInfoDO.getGoodsCases());
        return AppR.ok(map1);
    }


    /*    入库环节       */


    /**
     * 添加入库单
     * @param providerId 供应商id
     * @param logisticsCompany 物流公司
     * @param plateNumbers  车牌号
     * @param traynum  托盘数
     * @param cartons  箱数
     * @param category 品类
     * @param staffId  预检员id
     * @return
     */
    @PostMapping("add")
    @ResponseBody
    public AppR putStorage(@RequestParam Long providerId,
                                 @RequestParam(required = false) String logisticsCompany,
                                 @RequestParam(required = false) String plateNumbers,
                                 @RequestParam(required = false) Integer traynum,
                                 @RequestParam(required = false) Integer cartons,
                                 @RequestParam(required = false) String category,
                                 @RequestParam(required = false) String remark,
                                 @RequestParam(required = false) String driverPhone,
                                 @RequestParam(required = false) String driverName,
                                 @RequestParam(required = false) String putType,
                                 @RequestParam(required = false) String shopName,
                                 @RequestParam Long staffId){
        if(staffUserService.get(staffId)==null)
            return AppR.error(CodeUtils.NO_USER,"没有找到该用户");


        if(providerInfoService.get(providerId)==null)
            return AppR.error(CodeUtils.NO_PROVIDER,"没有找到该供应商");

        Map<String,Object> map = new HashMap<>();
        map.put("status","140001");
        map.put("staffId",staffId);
        List<PutStorageDO> list = putStorageService.list(map);
//        if(list.size()==0){
//            return AppR.ok(1);
//        }

        PutStorageDO putStorageDO = new PutStorageDO();

        if(putType.equals("142003")){
            Map<String,Object> objectMap = new HashMap<>();
            objectMap.put("shopName",shopName);
            objectMap.put("providerId",providerId);
            List<ShopDO> shopDOList = shopService.list(objectMap);
            if(shopDOList.size()==1){
                putStorageDO.setShopId(shopDOList.get(0).getShopId());
            }else {
                AppR.error(CodeUtils.SHOP_ERROR,"门店输入错误");
            }

        }
        putStorageDO.setCategory(category);
        putStorageDO.setCreateTime(new Date());
        putStorageDO.setDriverName(driverName);
        putStorageDO.setDriverPhone(driverPhone);
        putStorageDO.setRemark(remark);
        putStorageDO.setProviderId(providerId);
        putStorageDO.setStaffId(staffId);
        putStorageDO.setCartons(cartons);

        putStorageDO.setPutType(putType);
        putStorageDO.setTraynum(traynum);
        putStorageDO.setPlateNumbers(plateNumbers);
        putStorageDO.setStatus("140001");
        putStorageDO.setLogisticsCompany(logisticsCompany);
        putStorageService.save(putStorageDO);
        return AppR.ok(putStorageDO);
    }






    /**
     * 添加入库详情
     * @param goodsCode 商品码
     * @param putUnit  单位
     * @param boxCode  箱码
     * @param goodsWigth 重量
     * @param goodsStandard  商品规格
     * @param trayCode 拖码
     * @return
     */
    @PostMapping("/detail")
    @ResponseBody
    public AppR addDetail(@RequestParam String goodsCode,
                          @RequestParam(required = false) String putUnit,
                          @RequestParam(required = false) String boxCode,
                          @RequestParam(required = false) Double goodsWigth,
                          @RequestParam(required = false) String goodsStandard,
                          @RequestParam(required = false) String trayCode,
                          //@RequestParam Integer goodsNumber,
                          @RequestParam(required = false) Date dueTime,
                          @RequestParam Long putId,
                          @RequestParam(required = false) Integer boxNum,
                          @RequestParam(required = false) Integer hashNum){

        PutStorageDO putStorageDO=putStorageService.get(putId);
        if(putStorageDO==null)
            return AppR.error(CodeUtils.NO_PUT,"入库单不存在");


        Map<String,Object> map = new HashMap<>();
        map.put("goodsCode",goodsCode);
        map.put("providerId",putStorageDO.getProviderId());


        GoodsInfoDO goodsInfoDO =goodsInfoService.getGoodsBySku(map);

        if(goodsInfoDO==null)
            return AppR.error(CodeUtils.NO_GOODS,"没有录入商品");


        if(tGoodsAllocationService.getTargetAllocation(trayCode)!=null)
            return AppR.error(CodeUtils.trayCode_exist,"托盘已经存在");


        //SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
         //Date  currdate = format.parse(dueTime);
        PutStorageDetailDO putStorageDetailDO = new PutStorageDetailDO();
        //System.out.println(dueTime);
        if(goodsInfoDO.getDateType().equals("141001")){
            Calendar ca = Calendar.getInstance();
            ca.setTime(dueTime);
            ca.add(Calendar.DATE, goodsInfoDO.getGoodsGuarantePeriod());
            System.out.println(ca.getTime());
            putStorageDetailDO.setOutTime(ca.getTime());
        }else if(goodsInfoDO.getDateType().equals("141002")){
            putStorageDetailDO.setOutTime(dueTime);
        }

        if(boxNum==null){
        boxNum=0;
        }
        if(hashNum==null){
            hashNum=0;
        }
        putStorageDetailDO.setGoodsNumber(boxNum*goodsInfoDO.getGoodsCases()+hashNum);
        putStorageDetailDO.setGoodsCode(goodsCode);
        putStorageDetailDO.setPutUnit(putUnit);
        putStorageDetailDO.setBoxCode(boxCode);
        putStorageDetailDO.setPutTime(new Date());
        putStorageDetailDO.setGoodsWigth(goodsWigth);
        putStorageDetailDO.setGoodsStandard(goodsInfoDO.getGoodsStandard());
        putStorageDetailDO.setBoxNum(boxNum);
        putStorageDetailDO.setHashNum(hashNum);
        putStorageDetailDO.setGoodsId(goodsInfoDO.getGoodsId());
        putStorageDetailDO.setGoodsStandard(goodsInfoDO.getGoodsStandard());
        putStorageDetailDO.setPutDetailStatus("121001");
        putStorageDetailDO.setTrayCode(trayCode);
        putStorageDetailDO.setPutId(putId);
        //putStorageDetailDO.setGoodsNumber(goodsNumber);
        putStorageDetailService.save(putStorageDetailDO,putStorageDO.getProviderId(),putStorageDO.getPutType());
        return AppR.ok(putStorageDetailDO);
    }


    /**
     * 完成预检
     * @param staffId
     * @param putId
     * @return
     */
    @PostMapping("/finishPreflight")
    @ResponseBody
    public AppR finishPreflight(@RequestParam Long staffId,@RequestParam Long putId){
        if(staffUserService.get(staffId)==null){
           return AppR.error(CodeUtils.NO_USER,"用户不存在");
        }

        PutStorageDO putStorageDO =putStorageService.get(putId);
        if(putStorageDO==null)
          return   AppR.error(CodeUtils.NO_PUT,"入库单不存在");
        putStorageDO.setStatus("140002");
        putStorageDO.setStaffId(staffId);
        putStorageService.update(putStorageDO);
        Map<String,Object> map = new HashMap<>();
        map.put("putId",putId);
        List<PutStorageDetailDO> putStorageDetailDOList =putStorageDetailService.list(map);
        PutStorageDto putStorageDto = new PutStorageDto();
        putStorageDto.setCartons(putStorageDO.getCartons());
        putStorageDto.setCategory(putStorageDO.getCategory());
        putStorageDto.setCreateTime(putStorageDO.getCreateTime());
        putStorageDto.setForkliftId(putStorageDO.getForkliftId());
        putStorageDto.setPorterId(putStorageDO.getPorterId());
        putStorageDto.setLogisticsCompany(putStorageDO.getLogisticsCompany());
        putStorageDto.setStatus(putStorageDO.getStatus());
        putStorageDto.setPlateNumbers(putStorageDO.getPlateNumbers());
        putStorageDto.setProviderId(putStorageDO.getProviderId());
        putStorageDto.setPutId(putId);
        putStorageDto.setPutStorageDetailDOList(putStorageDetailDOList);
        putStorageDto.setStaffId(putStorageDO.getStaffId());
        putStorageDto.setTraynum(putStorageDO.getTraynum());
        return AppR.ok(putStorageDto);

    }




    /**
     * 搬运工根据托盘码获取目标货位信息货位
     * @param trayCode 托盘码
     * @return
     */
    @GetMapping("/getAllocation")
    @ResponseBody
    public AppR getAllocation(@RequestParam String trayCode ){

        return AppR.ok(tGoodsAllocationService.getTargetAllocationGoods(trayCode));
    }


    /**
     * 根据入库单详情ID ，修改入库单详情
     */
    @PostMapping("/update/storageDetail")
    @ResponseBody
    public AppR updatePutDetail(@RequestParam Long putDetailId,
                                @RequestParam(required = false) String goodsCode,
                                @RequestParam(required = false) String putUnit,
                                @RequestParam(required = false) String boxCode,
                                @RequestParam(required = false) Double goodsWigth,
                                @RequestParam(required = false) String goodsStandard,
                                @RequestParam(required = false) String trayCode,
                                @RequestParam(required = false) Integer goodsNumber,
                                @RequestParam Long putId){
        PutStorageDO putStorageDO=putStorageService.get(putId);
        if(putStorageDO==null)
            return AppR.error(CodeUtils.NO_PUT,"入库单不存在");

        GoodsInfoDO goodsInfoDO =null;
        if(goodsCode!=null){
            Map<String,Object> map = new HashMap<>();
            map.put("goodsCode",goodsCode);
            map.put("providerId",putStorageDO.getProviderId());
            goodsInfoDO=goodsInfoService.getGoodsBySku(map);
            if(goodsInfoDO==null)
                return AppR.error(CodeUtils.NO_GOODS,"没有录入商品");
        }

        PutStorageDetailDO putStorageDetailDO = new PutStorageDetailDO();
        putStorageDetailDO.setGoodsStandard(goodsInfoDO.getGoodsStandard());
        putStorageDetailDO.setPutDetailId(putDetailId);
        putStorageDetailDO.setGoodsCode(goodsCode);
        putStorageDetailDO.setPutUnit(putUnit);
        putStorageDetailDO.setBoxCode(boxCode);
        putStorageDetailDO.setPutTime(new Date());
        putStorageDetailDO.setGoodsWigth(goodsWigth);
        putStorageDetailDO.setGoodsId(goodsInfoDO.getGoodsId());
        putStorageDetailDO.setGoodsStandard(goodsStandard);
        putStorageDetailDO.setPutDetailStatus("121001");
        putStorageDetailDO.setTrayCode(trayCode);
        putStorageDetailDO.setPutId(putId);
        putStorageDetailDO.setGoodsNumber(goodsNumber);
        if(putStorageDetailService.update(putStorageDetailDO)==1)
        return AppR.ok();
        else
            return AppR.error(CodeUtils.EDIT_FAILE,"保存失败");
    }

    /**
     * 获取进库单商品信息
     * @param staffId
     * @return
     */
    @GetMapping("getGoodsByPut")
    @ResponseBody
    public AppR getGoodsByPut(@RequestParam Long staffId){
        /**
         * 查询入库为录入完成的入库单
         */
        Map<String,Object> mapPut = new HashMap<>();
        mapPut.put("staffId",staffId);
        mapPut.put("status","140001");
        List<PutStorageDO> putStorageDOList = putStorageService.list(mapPut);
        if(putStorageDOList.size()==0){
            return AppR.ok("没有未录入商品入库单");
        }




        //System.out.println(JSON.toJSON(putStorageDOList));
        Map<String,Object> map = new HashMap<>();
        if(putStorageDOList.get(0)!=null){
            map.put("list",putStorageDetailService.getPutDetail(putStorageDOList.get(0).getPutId()));
            map.put("putStorageDO",putStorageService.get(putStorageDOList.get(0).getPutId()));
        }

        return AppR.ok(map);
    }






    /**
     * 完成搬运
     * @param trayCode
     * @param porterId
     * @return
     */
    @GetMapping("/finishCarry")
    @ResponseBody
    public AppR finishCarry(@RequestParam String trayCode,@RequestParam Long porterId,@RequestParam Long allocationNumber ){
        if(staffUserService.get(porterId)==null){
          return   AppR.error(CodeUtils.NO_USER,"用户不存在");
        }
        Map<String,Object> map = new HashMap<>();
        map.put("trayCode",trayCode);
        map.put("putDetailStatus","121001");
        PutStorageDetailDO putStorageDetailDO=putStorageDetailService.detailByTrayCode(map);
       // System.out.println("putStorageDetailDO:"+JSON.toJSON(putStorageDetailDO));
       // System.out.println(putStorageDetailDO==null);
        if (putStorageDetailDO==null){
            //System.out.println("1111111");
          return   AppR.error(CodeUtils.NO_TARGET_ARE,"不是目标货位");
        }


        if(!allocationNumber.equals(putStorageDetailDO.getTargetGoodsArea()))
          return   AppR.error(CodeUtils.NO_TARGET_ARE,"不是目标货位");

        if(!putStorageDetailDO.getPutDetailStatus().equals("121001"))
          return   AppR.error(CodeUtils.finishCarry,"搬运已完成");
        putStorageDetailDO.setPutDetailStatus("121002");
        putStorageDetailService.update(putStorageDetailDO);
        return AppR.ok(1);
    }


    /**
     * 完成入货
     * @param trayCode
     * @return
     */
    @GetMapping("/finishPut")
    @ResponseBody
    public AppR finishPut(@RequestParam String trayCode,@RequestParam Long forkliftId ,@RequestParam Long allocationNumber){

        if(staffUserService.get(forkliftId)==null){
          return   AppR.error(CodeUtils.NO_USER,"用户不存在");
        }
        Map<String,Object> map = new HashMap<>();
        map.put("trayCode",trayCode);
        //map.put("putDetailStatus","121002");
        PutStorageDetailDO putStorageDetailDO=putStorageDetailService.detailByTrayCode(map);
        if(putStorageDetailDO==null){
            return   AppR.error(CodeUtils.NO_TARGET_ARE,"该商品没有添加托盘");
        }

        if(putStorageDetailDO.getPutDetailStatus().equals("121004"))
            return   AppR.error(CodeUtils.NO_TARGET_ARE,"该商品没有货位");

        if(putStorageDetailDO.getPutDetailStatus().equals("121003"))
            return   AppR.error(CodeUtils.NO_TARGET_ARE,"该商品已入库");


        if(!allocationNumber.equals(putStorageDetailDO.getTargetGoodsArea()))
          return   AppR.error(CodeUtils.NO_TARGET_ARE,"不是目标货位");

        putStorageDetailService.updatePut(trayCode,forkliftId);
        return AppR.ok(1);
    }

    /**
     * 根据用户id获取消息
     *
     */
    @GetMapping("getMessage")
    @ResponseBody
    public AppR getMessage(@RequestParam Long staffId){
        Map<String,Object> mapList = new HashMap<>();
        mapList.put("receiver",staffId);
        List<MessageDO> messageDOList =messageService.list(mapList);
        Map<String,Object> map = new HashMap<>();
        map.put("list",messageDOList);
        return AppR.ok(map);
    }

    /**
     * 根据putid获取没有货位的入库单详情
     */
    @GetMapping("getPutDetail")
    @ResponseBody
    public AppR getPutDetail(@RequestParam Long putId){
        Map<String,Object> mapList = new HashMap<>();
        mapList.put("putId",putId);
        mapList.put("putDetailStatus","121004");
        Map<String,Object> map = new HashMap<>();
        map.put("list",putStorageDetailService.list(mapList));
        return AppR.ok(map);
    }


    /**
     *退货/残次品入库
     */
    @GetMapping("specialPut")
    @ResponseBody
    public AppR specialPut(@RequestParam Long putId,@RequestParam String allocationNumber){
        PutStorageDO putStorageDO = putStorageService.get(putId);
        if(!putStorageDO.getStatus().equals("140001")){
            return AppR.error(CodeUtils.PUT_FINSH,"已入库");
        }
        int msg = putStorageService.updateSpecial(putStorageDO,allocationNumber );
        if(msg==-1){
            return AppR.error(CodeUtils.NO_ARE,"货位错误");
        }if (msg==-2){
            return AppR.error(CodeUtils.NOT_Special,"不是特殊入库单");
        }
        return AppR.ok();
    }


    /**
     * 查询门店
     * @param shopName
     * @return
     */
    @GetMapping("getShop")
    @ResponseBody
    public AppR getShop(@RequestParam(required = false) String shopName){
        Map<String,Object> map = new HashMap<>();
        map.put("shopName",shopName);
        return AppR.ok(shopService.list(map));
    }
}
